import os
import subprocess

import docx
from docx import Document
from docx.enum.text import WD_UNDERLINE
from docx.shared import RGBColor

def remove_columns(doc):
    for section in doc.sections:
        # 清除分栏设置
        sectPr = section._sectPr
        cols = sectPr.xpath('./w:cols')
        if cols:
            for col in cols:
                col.getparent().remove(col)

def remove_lines_with_words(doc, words):
    paragraphs = doc.paragraphs
    for paragraph in paragraphs:
        if any(word in paragraph.text for word in words):
            p = paragraph._element
            p.getparent().remove(p)

def remove_empty_lines(doc):
    paragraphs = doc.paragraphs
    for paragraph in reversed(paragraphs):
        if not paragraph.text.strip() and not any(run.element.xml for run in paragraph.runs):
            p = paragraph._element
            p.getparent().remove(p)

def set_paragraph_indent(doc, left_indent, right_indent):
    for paragraph in doc.paragraphs:
        paragraph.paragraph_format.left_indent = left_indent
        paragraph.paragraph_format.right_indent = right_indent

def highlight_with_words(doc, words_to_highlight):
    for paragraph in doc.paragraphs:
        for run in paragraph.runs:
            for word in words_to_highlight:
                if word in run.text:
                    # 分割当前运行文本，以便高亮指定的单词
                    text_parts = run.text.split(word)
                    # 清除当前运行
                    run.clear()
                    for part in text_parts:
                        # 添加分割后的文本
                        run = paragraph.add_run(part)
                        # 如果这部分文本包含指定的单词，则高亮
                        if part == word:
                            run.font.bold = True
                            run.font.underline = WD_UNDERLINE.SINGLE
                            run.font.color.rgb = RGBColor(255, 0, 0)  # 红色
                            run.font.size = doc.styles['Normal'].font.size

# 加载docx文档
doc = Document('全程指导.docx')

# 1. 取消文档中的所有分栏
remove_columns(doc)

# 2. 删除包含指定字的行
words_to_remove = ['您现在的位置', '张友生']
remove_lines_with_words(doc, words_to_remove)

# 3. 去除所有空行，但保留包含图片的行
remove_empty_lines(doc)
set_paragraph_indent(doc, 720, 720)


# 5. 高亮指定的单词
# words_to_highlight = ['教育专家提示']
# highlight_with_words(doc, words_to_highlight)


# 保存修改后的文档
doc.save('全程指导-after.docx')
